/**
 * Copyright 2011 classic-commerce
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package ca.ioniq.client.presenter;

import ca.ioniq.client.event.LoginEvent;
import ca.ioniq.client.event.LoginEventHandler;
import ca.ioniq.client.view.HeaderView;
import ca.ioniq.client.widget.header.LoginWidget;
import ca.ioniq.shared.Credentials;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * This presenter handlers interactions from the LoginWidget and
 * CartSummaryWidget.
 *
 * @author <a href="mailto:richard@ioniq.ca">Richard Mutezintare</a>
 */
public class HeaderViewPresenter implements Presenter {
    private HeaderView headerView;
    private EventBus eventBus;

    public HeaderViewPresenter(final HeaderView headerView, final EventBus eventBus) {
        this.headerView = headerView;
        this.eventBus = eventBus;

        registerEvents();

        // handler user sending credentials to log into the app
        headerView.getLoginWidget().getLoginLink().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                String username = headerView.getLoginWidget().getUsername();
                String password = headerView.getLoginWidget().getPassword();

                if (username.length() == 0) {
                    // TODO add error message for username
                } else if (password.length() == 0) {
                    // TODO add error message for password
                } else {
                    eventBus.fireEvent(new LoginEvent(new Credentials(username, password)));
                }
            }
        });

        // handler user wishing to login
        headerView.getHeaderMenu().getLoginLink().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                LoginWidget loginWidget = headerView.getLoginWidget();
                if(!loginWidget.isVisible()) {
                    loginWidget.setVisible(true);
                }

                // set focus on the username text box
                loginWidget.getUsernameBox().setFocus(true);

                // TODO implements a "remember feature"
            }
        });
    }

    private void registerEvents() {
        eventBus.addHandler(LoginEvent.TYPE, new LoginEventHandler() {
            public void onLogin(LoginEvent event) {
                // connect to remote service with credentials
                if (authenticate(event.getCredentials())) {
                    // TODO show welcome widget with customized messages with username
                } else {
                    // TODO show authentication error in errorWidget
                }
            }
        });
    }

    /**
     * Class remote server with authentication params
     *
     * @param loginCredentials contains username and password
     * @return boolean true if authentication successful
     *                              false otherwise
     */
    private boolean authenticate(Credentials loginCredentials) {
        // TODO this does not seem right....Fix this!!!!! This should call an external service...
        try {
            RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "");

            requestBuilder.setCallback(new LoginRequestCallBack());
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return false;
    }


    public void onCartSummaryClicked() {
        // TODO implement me
        // when cart link is clicked; show the cart summary view in the
        // main content view and scroll to position

    }


    public void go(HasWidgets container) {
        // TODO go to MainContentView and set focus

    }

    private class LoginRequestCallBack implements RequestCallback {

        public void onResponseReceived(Request request, Response response) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        public void onError(Request request, Throwable exception) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }
}
